'use strict'
//axios 二次封装  其目的 方便 后期改动 添加拦截器  使用promise  解决异步不同步问题
import axios from 'axios'
import Vue from 'vue'
import router from '../router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
import merge from 'lodash/merge'
import qs from 'qs'

Vue.use(ElementUI)
axios.interceptors.request.use(config => {
    config.headers['token'] = window.$cookies.get('token_back') // 请求头带上token
    return config
}, error => {
    return Promise.reject(error)
})
axios.interceptors.response.use(response => {
    return response
}, error => {
    return Promise.resolve(error.response)
})

function checkStatus(response) {
    // 如果http状态码正常，则直接返回数 据
    if (response && response.status === 401) { // 401, token失效

        window.$cookies.remove('token_back')
        console.log(window.$cookies.get('token_back'))
        ElementUI.MessageBox.alert('登录异常', '登录异常', {
            confirmButtonText: '确定',
            callback: action => {
                router.push({name: 'login'}, () => {
                    location.reload() // 刷新页面, 清空整站临时存储数据
                })
            }
        });
    }
    else if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
        return response.data
        // 如果不需要除了data之外的数据，可以直接 return response.data
    }
    // 异常状态下，把错误信息返回去
    return {
        status: -404,
        msg: '网络异常'
    }
}
function getHead(url) {
    const arr = ['login']; //不需要header 的接口
    if (url.indexOf(...arr) == -1 && window.$cookies.get('token_back')) {
        const val =  window.$cookies.get('token_back')
        let header = {
            'Authorization': 'Bearer ' + val
        }
        return header
    }
    return {}
}
function checkCode(res) {
    // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
    if (res.status === -404) {
        return
        // alert(res.msg)
    }
    return res
}

export default {
    exportRate(downUrl,data) {
        console.log(data)
        return axios({
            url: downUrl,
            method: 'get',
            headers: Object.assign(getHead(downUrl),{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}),
            params:data,
            responseType: 'blob'  //二进制流
        })
    },
    post(url, data) {
        return axios({
            method: 'post',
            url,
            data: qs.stringify(data),
            // data,
            timeout: 10000,
            headers: Object.assign(getHead(url),{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
        }).then(
            (response) => {
                return checkStatus(response)
            }
        ).then(
            (res) => {
                return checkCode(res)
            }
        )
    },
    put(url, data) {
        return axios({
            method: 'put',
            url,
            data: qs.stringify(data),
            timeout: 10000,
            headers: Object.assign(getHead(url),{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
        }).then(
            (response) => {
                return checkStatus(response)
            }
        ).then(
            (res) => {
                return checkCode(res)
            }
        )
    },
    putJson(url, data) {
        return axios({
            method: 'put',
            url,
            data: qs.stringify(data),
            timeout: 10000,
            headers: Object.assign(getHead(url),{'Content-Type': 'application/json;charset=UTF-8',})

        }).then(
            (response) => {
                return checkStatus(response)
            }
        ).then(
            (res) => {
                return checkCode(res)

            }
        )
    },
    putJson1(url, data) {
        return axios({
            method: 'put',
            url,
            data: data,
            timeout: 10000,
            headers: Object.assign(getHead(url),{'Content-Type': 'application/json;charset=UTF-8',})

        }).then(
            (response) => {
                return checkStatus(response)
            }
        ).then(
            (res) => {
                return checkCode(res)

            }
        )
    },
    postJson(url, data) {
        return axios({
            method: 'post',
            url,
            data: data,
            timeout: 10000,
            headers: Object.assign(getHead(url),{'Content-Type': 'application/json;charset=UTF-8',})
        }).then(
            (response) => {
                return checkStatus(response)
            }
        ).then(
            (res) => {
                return checkCode(res)
            }
        )
    },
    get(url, params) {
        return axios({
            method: 'get',
            url,
            params: params, // get 请求时带的参数
            timeout: 10000,
            headers: Object.assign(getHead(url),{'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
        }).then(
            (response) => {
                return checkStatus(response)
            }
        ).then(
            (res) => {
                return checkCode(res)
            }
        )
    },
    delete(url, params) {
        return axios({
            method: 'delete',
            url,
            params: params, // get 请求时带的参数
            timeout: 10000,
            headers: Object.assign(getHead(url),{'Content-Type': 'application/json;charset=UTF-8'})
        }).then(
            (response) => {
                return checkStatus(response)
            }
        ).then(
            (res) => {
                return checkCode(res)
            }
        )
    },
    adornParams(params = {}, openDefultParams = true) {
        var defaults = {
            't': new Date().getTime()
        }
        return openDefultParams ? _.merge(defaults, params) : params
    },
    adornData(data = {}, openDefultdata = true, contentType = 'json') {
        var defaults = {
            't': new Date().getTime()
        }
        data = openDefultdata ? merge(defaults, data) : data
        return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
    }
}
